package io.renren.modules.dangan.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.lowagie.text.*;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import com.lowagie.text.pdf.codec.TiffImage;
import io.renren.modules.dangan.bean.BookMark;
import io.renren.modules.dangan.entity.DaJnmlbEntity;
import io.renren.modules.dangan.entity.DaServerEntity;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @auther guqianbin
 * @date 2019/8/4 21:30
 **/
public class FileUtils {

    public static void main(String[] args) {
        try {
            File file=new File("F:\\dangan\\jb\\2012\\0100061\\00000001.pdf");
            String newFilePath="F:\\dangan\\jb\\2012\\0100061\\00000001warter.pdf";
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFilePath));
            //TODO 水印加载错误 PDF header signature not found
            PdfReader reader = new PdfReader(file.getAbsolutePath());
            PdfStamper stamper = new PdfStamper(reader, bos);
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte content;
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            for (int i = 1; i < total; i++) {
                content = stamper.getOverContent(i);// 在内容上方加水印
                //			 content = stamper.getUnderContent(i);//在内容下方加水印
                Rectangle rectangle = reader.getPageSize(i);
                gs.setFillOpacity(0.2f);
                gs.setStrokeOpacity(0.6f);
                content.setGState(gs);
                content.beginText();
                content.setColorFill(Color.lightGray);
                //修改按图片比例设置文字大小
                content.setFontAndSize(base, rectangle.getWidth() / 13);
                content.setTextMatrix(70, 200);
                content.showTextAligned(Element.ALIGN_CENTER, "宁波市自然资源和规划局", rectangle.getWidth() / 2,
                        rectangle.getHeight() / 2, 55);
                content.setColorFill(Color.BLACK);
                content.setFontAndSize(base, rectangle.getWidth() / 50);
                content.showTextAligned(Element.ALIGN_CENTER, "下载时间："
                        + "testName" + "", rectangle.getWidth() / 2, 15, 0);
                content.endText();

            }
            stamper.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writerFile(HttpServletResponse response, File file) throws FileNotFoundException {
        if (file != null) {
            BufferedInputStream bis = null;
            byte[] buff = new byte[1024];
//            response.setDateHeader("Expires", 0);
//            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
//            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
//            response.setHeader("Pragma", "no-cache");
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "inline;filename=" + file.getName());
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    outputStream.write(buff, 0, i);
                    outputStream.flush();
                    i = bis.read(buff);
                }
            } catch (IOException e) {
                throw new FileNotFoundException("输出文件时报错：" + e.getMessage());
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            throw new FileNotFoundException("文件没有找到");
        }
    }


    public static File tifToPdf(File tifFile) throws IOException {
        // 创建一个文档对象
        Document doc = new Document();
        int pages = 0, comps = 0;
        RandomAccessFileOrArray ra = null;
        String pdfPath = tifPath2PdfPath(tifFile.getAbsolutePath());
        File pdfFile = new File(pdfPath);
        try {
            try {
                ra = new RandomAccessFileOrArray(new FileInputStream(tifFile));
                comps = TiffImage.getNumberOfPages(ra);
            } catch (Throwable e) {
                System.out.println("Exception in " + tifFile.getAbsolutePath() + " " + e.getMessage());
            }
            // 定义输出文件的位置
            PdfWriter.getInstance(doc, new FileOutputStream(pdfFile.getAbsolutePath()));
            // 开启文档
            doc.open();

            Object localObject1 = null;
            Object localObject2 = null;
            com.lowagie.text.Image localImage1 = null;
            URL paramURL = Utilities.toURL(tifFile.getAbsolutePath());
            try {
                if (paramURL.getProtocol().equals("file")) {
                    localObject2 = paramURL.getFile();
                    localObject2 = Utilities
                            .unEscapeURL((String) localObject2);
                    localObject1 = new RandomAccessFileOrArray(
                            (String) localObject2);
                } else {
                    localObject1 = new RandomAccessFileOrArray(paramURL);
                }

                int pageNums = TiffImage
                        .getNumberOfPages((RandomAccessFileOrArray) ra);
                if (pageNums > 0) {
                    for (int i = 1; i <= pageNums; i++) {
                        localObject2 = TiffImage.getTiffImage(
                                (RandomAccessFileOrArray) localObject1, i);
                        com.lowagie.text.Image jpg = (com.lowagie.text.Image) localObject2;
                        // 获得图片的高度
                        float heigth = jpg.getHeight();
                        float width = jpg.getWidth();
                        // 合理压缩，h>w，按w压缩，否则按w压缩
                        float percent = getPercent(heigth, width);

                        // 设置图片居中显示
                        jpg.setAlignment(Image.MIDDLE);
                        // 按百分比显示图片的比例
                        if (width > heigth) {
                            doc.setPageSize(PageSize.A3.rotate());
                            doc.newPage();
                            percent = (1191 / width * 100);
                            jpg.scalePercent(percent);
                            //System.out.println("缩小后的大小h:"+jpg.getScaledHeight()+"w:"+jpg.getScaledWidth());
                            doc.setPageSize(PageSize.A3.rotate());
                        } else {
                            percent = (595 / width * 100);
                            jpg.scalePercent(percent);
                            doc.setPageSize(PageSize.A4);
                        }
                        doc.setMargins(0, 0, 0, 0);
                        doc.add(jpg);
                    }
                }
                if (localObject1 != null)
                    ((RandomAccessFileOrArray) localObject1).close();

            } finally {
                if (localObject1 != null) {
                    ((RandomAccessFileOrArray) localObject1).close();
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (doc != null) {
                doc.close();
            }
            ra.close();
        }
        return pdfFile;
    }

    /**
     * 第一种解决方案 在不改变图片形状的同时，判断，如果h>w，则按h压缩，否则在w>h或w=h的情况下，按宽度压缩
     *
     * @param h
     * @param w
     * @return
     */

    public static int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        if (h > w) {
            p2 = 210 / h * 297;
        } else {
            p2 = 210 / w * 297;
        }
        p = Math.round(p2);
        return p;
    }

    public static boolean isTifFile(File file) {
        if(file.getName().toLowerCase().contains(".tif")){
            return true;
        }
        return false;
    }

    public static String tifPath2PdfPath(String tifPath) {
        if (tifPath.endsWith(".tiff")) {
            return tifPath.replace(".tiff", ".pdf");
        } else {
            if(tifPath.endsWith(".TIF")){
                return tifPath.replace(".TIF", ".pdf");
            }else{
                return tifPath.replace(".tif", ".pdf");
            }
        }
    }
    public static String getFileFtpPath(DaServerEntity xtServer,DaJnmlbEntity tifpath){
        String remotePath="";
        //文件名，以tif结尾的,路径的分隔符可能是/和\\两种情况,应为有/doc0801/C07173\00000001.TIF 所以要根据这两个符号位置蓝判断
        int loc1 = tifpath.getLjmc().lastIndexOf("/");
        int loc2 = tifpath.getLjmc().lastIndexOf("\\");
        if(loc1>loc2){
            //路径的开头分带/和不带/的路径分隔符是\，开头不带分隔符\
            if(!tifpath.getLjmc().startsWith("/")){
                remotePath=xtServer.getDiskname().trim()+"/"+ tifpath.getLjmc().substring(0,tifpath.getLjmc().lastIndexOf("/"));
            }
            remotePath=xtServer.getDiskname().trim()+"/"+ tifpath.getLjmc().substring(0,tifpath.getLjmc().lastIndexOf("/"));
        }else {
            remotePath=xtServer.getDiskname().trim()+"\\"+ tifpath.getLjmc().substring(0,tifpath.getLjmc().lastIndexOf("\\"));
        }
        return remotePath+"/";
    }
    public static String getFileFtpPathJnml(DaServerEntity xtServer,DaJnmlbEntity tifpath){
        String remotePath="";
        //文件名，以tif结尾的,路径的分隔符可能是/和\\两种情况,应为有/doc0801/C07173\00000001.TIF 所以要根据这两个符号位置蓝判断
        int loc1 = tifpath.getLjmc().lastIndexOf("/");
        int loc2 = tifpath.getLjmc().lastIndexOf("\\");
        if(loc1>loc2){
            //路径的开头分带/和不带/的路径分隔符是\，开头不带分隔符\
            if(!tifpath.getLjmc().startsWith("/")){
                remotePath=xtServer.getDiskname().trim()+xtServer.getRelativepath()+"/"+ tifpath.getLjmc().substring(0,tifpath.getLjmc().lastIndexOf("/"));
            }
            remotePath=xtServer.getDiskname().trim()+xtServer.getRelativepath()+"/"+ tifpath.getLjmc().substring(0,tifpath.getLjmc().lastIndexOf("/"));
        }else {
            remotePath=xtServer.getDiskname().trim()+xtServer.getRelativepath()+"\\"+ tifpath.getLjmc().substring(0,tifpath.getLjmc().lastIndexOf("\\"));
        }
        return remotePath+"/";
    }
    public static String getJnmlFilePath(DaJnmlbEntity tifpath){
        String remotePath="";
        //文件名，以tif结尾的,路径的分隔符可能是/和\\两种情况,应为有/doc0801/C07173\00000001.TIF 所以要根据这两个符号位置蓝判断
        int loc1 = tifpath.getLjmc().lastIndexOf("/");
        int loc2 = tifpath.getLjmc().lastIndexOf("\\");
        if(loc1>loc2){
            //路径的开头分带/和不带/的路径分隔符是\，开头不带分隔符\
            if(!tifpath.getLjmc().startsWith("/")){
                remotePath= tifpath.getLjmc().substring(0,tifpath.getLjmc().lastIndexOf("/"));
            }
            remotePath= tifpath.getLjmc().substring(0,tifpath.getLjmc().lastIndexOf("/"));
        }else {
            remotePath= tifpath.getLjmc().substring(0,tifpath.getLjmc().lastIndexOf("\\"));
        }
        return remotePath+"/";
    }

    public static String getFtpFileName(String filePath){
        String fileName="";
        //文件名，以tif结尾的,路径的分隔符可能是/和\\两种情况,应为有/doc0801/C07173\00000001.TIF 所以要根据这两个符号位置蓝判断
        int loc1 = filePath.lastIndexOf("/");
        int loc2 =filePath.lastIndexOf("\\");
        if(loc1>loc2){
            //路径的开头分带/和不带/的路径分隔符是\，开头不带分隔符\
            fileName= filePath.substring(loc1+1,filePath.length());
        }else {
            fileName=filePath.substring(loc2+1,filePath.length());
        }
        return fileName;
    }
    public static String buildFilePath(DaServerEntity daServerEntity, DaJnmlbEntity daJnmlbEntity) {
        StringBuilder sb = new StringBuilder();
        sb.append(daServerEntity.getDiskname());
        sb.append(daServerEntity.getRelativepath());
        if(daJnmlbEntity.getLjmc().startsWith("\\")
                ||daJnmlbEntity.getLjmc().startsWith("/")){
            sb.append(daJnmlbEntity.getLjmc());
        }else{
            sb.append("\\");
            sb.append(daJnmlbEntity.getLjmc());
        }
        return sb.toString();
    }

    public static String buildFilePath(DaServerEntity daServerEntity, String lj) {
        StringBuilder sb = new StringBuilder();
        sb.append(daServerEntity.getDiskname());
        sb.append(daServerEntity.getRelativepath());
        if(!lj.startsWith("//")){
            sb.append("//");
        }
        sb.append(lj);
        return sb.toString();
    }

    public static String buildFilePath(DaServerEntity daServerEntity) {
        StringBuilder sb = new StringBuilder();
            sb.append(daServerEntity.getDiskname());
            sb.append(daServerEntity.getRelativepath());


        return sb.toString();
    }


    /**
     * pdf加水印，并返回新路径
     *
     * @param file
     * @param waterMarkName
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static File setWatermark(File file,
                                    String waterMarkName) throws DocumentException,
            IOException {
        String filePath = file.getAbsolutePath();
        String waterPdfPath = filePath.substring(0, filePath.lastIndexOf('.')) + "water.pdf";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(waterPdfPath));
        //TODO 水印加载错误 PDF header signature not found
        PdfReader reader = new PdfReader(file.getAbsolutePath());
        PdfStamper stamper = new PdfStamper(reader, bos);
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                BaseFont.EMBEDDED);
        PdfGState gs = new PdfGState();
        for (int i = 1; i < total; i++) {
            // 在内容上方加水印
            content = stamper.getOverContent(i);
            Rectangle rectangle = reader.getPageSize(i);
            gs.setFillOpacity(0.2f);
            gs.setStrokeOpacity(0.6f);
            content.setGState(gs);
            content.beginText();
            content.setColorFill(Color.lightGray);
            //修改按图片比例设置文字大小
            content.setFontAndSize(base, rectangle.getWidth() / 13);
            content.setTextMatrix(70, 200);
            content.showTextAligned(Element.ALIGN_CENTER, "宁波市自然资源和规划局", rectangle.getWidth() / 2,
                    rectangle.getHeight() / 2, 55);
            content.setColorFill(Color.BLACK);
            content.setFontAndSize(base, rectangle.getWidth() / 50);
            content.showTextAligned(Element.ALIGN_CENTER, "下载时间："+ DateUtil.format(new Date(),"yyyy-MM-dd hh:mm")
                    + waterMarkName + "", rectangle.getWidth() / 2, 15, 0);
            content.endText();

        }
        stamper.close();
        return new File(waterPdfPath);
    }



    /**
     * 更具pdf文件 ，读取文件的书签集合返回
     *
     * @param file
     * @return
     * @throws IOException
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static List<BookMark> getBookMarks(File file) throws IOException {
        List<BookMark> list = new ArrayList<>();
        PdfReader pdfReader = new PdfReader(file.getPath());
        List bookMarksList = SimpleBookmark.getBookmark(pdfReader);
        for (Object object : bookMarksList) {
            Map<String, Object> markMap = (Map<String, Object>) object;
            String title = (String) markMap.get("Title");
            String page = markMap.get("Page").toString().substring(0, 2).replace(" ", "");
            list.add(new BookMark(title, page));
        }
        return reOrderBookMarks(list);
    }

    /**
     * 对书签顺序进行倒置 1，2，3变成3，2，1
     *
     * @param list
     * @return
     */
    private static List<BookMark> reOrderBookMarks(List<BookMark> list) {
        int j = 1;
        int mid = list.size() / 2;
        int length = list.size();
        for (int i = 0; i < list.size(); i++) {
            if (i <= mid) {
                BookMark b = list.get(i);
                list.set(i, list.get(length - j));
                list.set(length - j, b);
                j++;
            }
        }
        return list;
    }

    public static String  getFilePath(){
        LocalDate localDate=LocalDate.now();
        int year=localDate.getYear();
        int month=localDate.getMonthValue();
        int day=localDate.getDayOfMonth();
        System.out.println(year+"-"+month+"-"+day);
        return "/"+year+"/"+month+"/"+day+"/";
    }

    public static   String  getFilePath(String prefix){
        LocalDate localDate=LocalDate.now();
        int year=localDate.getYear();
        int month=localDate.getMonthValue();
        int day=localDate.getDayOfMonth();
        System.out.println(year+"-"+month+"-"+day);
        return prefix+"/"+year+"/"+month+"/"+day+"/";
    }
}
